﻿using System;
using System.Collections.Generic;
using System.Xml;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using SolutionExtender.AppCode;
using SolutionExtender.Controls;
using SolutionExtender.Interfaces;

namespace McTools.SolutionExtender.UserQueryPlugin
{
    public class UserQueryConnector : IConnector
    {
        #region Variables

        /// <summary>
        /// IOrganization service to access CRM 2011 data
        /// </summary>
        private readonly IOrganizationService _service;

        #endregion Variables

        #region Constructor

        /// <summary>
        /// Initializes a new instance of class UserQueryConnector
        /// </summary>
        /// <param name="service">IOrganization service to access CRM 2011 data</param>
        public UserQueryConnector(IOrganizationService service)
        {
            _service = service;
        }

        #endregion Constructor

        #region Properties

        public string ObjectName
        {
            get { return "Saved view"; }
        }

        public string Description
        {
            get { return "You must have read access to Saved views you want to export (be sure to have at least shared read privilege)"; }
        }

        #endregion Properties

        #region Methods

        public List<ImportResult> Import(XmlNode data)
        {
            var queryObject =
                (UserQuery) XmlSerializerHelper.Deserialize(data.OuterXml, typeof (UserQuery));

            var query = new Entity("userquery");

            query["advancedgroupby"] = queryObject.AdvancedGroupBy;
            query["columnsetxml"] = queryObject.ColumnSetXml;
            query["conditionalformatting"] = queryObject.ConditionalFormatting;
            query["description"] = queryObject.Description;
            query["fetchxml"] = queryObject.FetchXml;
            query["layoutxml"] = queryObject.LayoutXml;
            query["name"] = queryObject.Name;
            query["parentqueryid"] = queryObject.ParentQueryId;
            query["querytype"] = queryObject.QueryType;
            query["returnedtypecode"] = queryObject.ReturnedTypeCode;
            query.Id = queryObject.RecordId;

            if (query.Id == Guid.Empty)
            {
                _service.Create(query);
            }
            else
            {
                try
                {
                    _service.Retrieve("userquery", query.Id, new ColumnSet());
                    _service.Update(query);
                }
                catch (Exception)
                {
                    _service.Create(query);
                }
            }

            return null;
        }

        public IExportControl GetExportControl(IOrganizationService service)
        {
           return new UserQueryExportControl(_service);
        }

        public string GetRecordName(XmlNode node)
        {
            return node.SelectSingleNode("Name").InnerText;
        }

        #endregion Methods
    }
}
